<template>
  <div class="app-container">
    <div class="filter-container channel-info">
      <el-input
        v-model="params.channelName"
        placeholder="渠道名称"
        size="medium"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="params.creditNumber"
        placeholder="信用编码"
        size="medium"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <!-- <el-input
        v-model="params.blnEnterprise"
        placeholder="是否企业"
        size="medium"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      /> -->
      <el-select v-model="params.blnEnterprise" placeholder="是否企业" clearable size="medium" class="filter-item">
        <el-option
          v-for="item in blnEnterprises"
          :key="item.key"
          :label="item.value"
          :value="item.key"/>
      </el-select>
      <el-input
        v-model.number="params.contactsPhone"
        :maxlength="11" 
        onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"
        placeholder="联系电话"
        size="medium"
        style="width: 200px;"
        clearable
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="params.contactsUser"
        placeholder="联系人"
        size="medium"
        style="width: 200px;"
        clearable
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        size="medium"
        icon="el-icon-search"
        @click="handleFilter"
      >查询
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        size="medium"
        icon="el-icon-edit-outline"
        @click="handleCreate"
        v-show="userTypeCode != 2"
      >创建
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        size="medium"
        icon="el-icon-error"
        @click="resetParams"
      >重置
      </el-button>
    </div>
    <el-table :data="list" border style="width: 100%" v-loading="listLoading">
      <el-table-column type="index" align="center" label="序号" width="50"></el-table-column>
      <el-table-column prop="channelName" label="渠道名称" />
      <el-table-column prop="address" label="渠道地址" />
      <el-table-column prop="contactsUser" label="联系人" />
      <el-table-column prop="contactsPhone" label="联系电话" />
      <el-table-column prop="blnEnterprise" label="是否企业">
        <template slot-scope="{row}">
          <!-- <el-tag :type="row.blnEnterprise">
            {{ blnStatus(row.blnEnterprise) }}
          </el-tag> -->
          <el-tag type="success" v-if='row.blnEnterprise == 1'>是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="creditNumber" label="信用编码/身份证号" />
      <!-- <el-table-column prop="logo" label="企业LOGO" width="180">
        <template slot-scope="scope">
          <img src="//qf19h52dw.hn-bkt.clouddn.com/images/2020-08-17-deeb60d6f6b34394b5fa61377e12e197.jpg" max-width='100px' max-height="60px">
        </template>
      </el-table-column> -->
      <el-table-column
        prop="logo"
        header-align="center"
        align="center"
        label="企业LOGO">
        <template slot-scope="scope">
          <el-popover placement="top" title="" trigger="hover">
            <img style="max-height: 500px;max-width: 730px" :src="getImgUrl(scope.row.logo)" />
            <img slot="reference" :src="getImgUrl(scope.row.logo)" :alt="scope.row.logo" style="max-height: 50px;max-width: 130px"/>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120px">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleView(row)">
            详情
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)" v-show="userTypeCode != 2">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="params.page"
      :limit.sync="params.limit"
      @pagination="getList"
    />
    <!--编辑页面表单-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="channnel-info-dialog">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="120px"
        style="margin: 0 40px;padding-bottom: 20px;">
        <el-form-item label="渠道编码" prop="channelCode" v-if="dialogStatus!='create'">
          <el-input v-model="form.channelCode" disabled clearable/>
        </el-form-item>
        <el-form-item label="渠道名称" prop="channelName">
          <el-input v-model="form.channelName" :disabled="dialogStatus=='view'" clearable/>
        </el-form-item>
        <el-form-item label="渠道地址" prop="address">
          <el-input v-model="form.address" :disabled="dialogStatus=='view'" clearable/>
        </el-form-item>
        <el-form-item label="联系人" prop="contactsUser">
          <el-input v-model="form.contactsUser" :disabled="dialogStatus=='view'" clearable/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactsPhone">
          <el-input v-model.number="form.contactsPhone" :maxlength="11" :disabled="dialogStatus=='view'" onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"clearable/>
        </el-form-item>
        <el-form-item label="是否企业" :disabled="dialogStatus=='view'" prop="blnEnterprise">
          <!-- <el-select v-model="form.blnEnterprise" placeholder="请选择" clearable :disabled="isDisabled" style="width: 100%">
            <el-option
              v-for="item in blnEnterprises"
              :key="item.key"
              :label="item.value"
              :value="item.key"/>
          </el-select> -->
          <el-radio v-model="form.blnEnterprise" label="1">是</el-radio>
          <el-radio v-model="form.blnEnterprise" label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="信用编码" prop="creditNumber" v-if="form.blnEnterprise == 1":rules="[{ required: true, message: '信用编码必填'},{ validator: checkData, trigger: 'blur'}]">
          <el-input v-model="form.creditNumber" :disabled="dialogStatus=='view'" clearable/>
        </el-form-item>
        <el-form-item label="身份证号" prop="IDcard" v-if="form.blnEnterprise == 2">
          <el-input v-model="form.IDcard" :disabled="dialogStatus !='create'" clearable/>
        </el-form-item>
        <el-form-item label="管理员用户名" prop="userName" v-if="dialogStatus == 'create'" :rules="[{ required: true, message: '管理员用户名必填'},{ validator: checkData, trigger: 'blur'}]">
          <el-input v-model="form.userName" clearable/>
        </el-form-item>
        <el-form-item label="企业LOGO" v-if="form.blnEnterprise == 1">
          <img :src="getImgUrl(form.logo)" width="150" :height='150' v-if="dialogStatus=='view'"/>
          <upload :fileList="picFileList" :limit="1" :multiple="false" @getImg="getPicFileList" v-else></upload>
        </el-form-item>
      </el-form>
      <template v-if="dialogStatus==='create'||dialogStatus==='update'">
        <div v-if="dialogStatus" slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { addOrModifyChannel, getChannelList, deleteChannel } from '@/api/channel/channel'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Upload from "@/components/upload/index";
export default {
  name: 'Channel',
  components: { Pagination,Upload },
  data() {
    return {
      // headers: {
      //   authorization: ''
      // },
      getToken: '',
      picFileList: [],
      list: [],
      listLoading: false,
      isDisabled: false,
      dialogImageUrl: '',
      dialogVisible: false,
      imgList: [],
      total: 0,
      blnEnterprises: [{
        key: '1',
        value: '是'
      }, {
        key: '2',
        value: '否'
      }],
      params: {
        channelName: '',
        creditNumber: '',
        contactsUser: '',
        contactsPhone: '',
        blnEnterprise: '',
        page: 1,
        limit: 10
      },
      dialogStatus: '',
      form: {
        id: '',
        channelCode: '',
        name: '',
        address: '',
        contactsUser: '',
        contactsPhone: '',
        blnEnterprise: '',
        creditNumber: '',
        userName:'',
        logo: '',
        IDcard: ''
      },
      rules: {
        channelCode: [{ required: true, message: '渠道代码必填' }],
        channelName: [{ required: true, message: '渠道名称必填' }],
        address: [{ required: true, message: '渠道地址必填' }],
        contactsUser: [{ required: true, message: '请填写联系人' }],
        contactsPhone: [
          { required: true, message: '请填写联系电话' },
          { pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'},
        ],
        blnEnterprise: [{ required: true, message: '请选择是否企业' }],
        creditNumber: [{ required: true, message: '信用编码必填' }],
        IDcard: [
        { required: true, message: '身份证号必填' },
        { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur'}
        ],
        logo: [{ required: true, message: '企业LOGO必填' }],
        userName: [{ required: true, message: '请填写用户名' }]
      },
      dialogFormVisible: false,
      textMap: {
        view: '详情',
        update: '编辑',
        create: '新增'
      },
      userTypeCode: '',//用户角色UT001平台 UT002渠道 UT003企业
    }
  },
  created() {
    this.getList()
    this.userTypeCode = sessionStorage.getItem("userTypeCode").substring(4,5)  || '';
  },
  methods: {
    resetTemp() {
      this.form = {
        id: '',
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        blnEnterprise: '1',
        userName:'',
        IDcard: '',
        status: 'published'
      }
    },
    resetParams(){
      this.params = {
        channelName: '',
        creditNumber: '',
        contactsUser: '',
        contactsPhone: '',
        blnEnterprise: '',
        page: 1,
        limit: 10
      }
    },
    //table图片回显
    getImgUrl(icon){
      return "//"+icon;
    },
    handleFilter() {
      this.params.page = 1
      this.getList()
    },
    handleCreate() {
      this.picFileList = [];
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.isDisabled = false
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(!this.form.logo && this.form.blnEnterprise == 1){
            this.$message.warning('请上传logo图片!')
            return
          }
          if(this.form.blnEnterprise == 2){
            this.form.creditNumber = this.form.IDcard;
          }
          addOrModifyChannel(this.form).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      const element = this.list[index]
      const data = [element.id]
      this.$confirm('确定删除该条数据？','提示', {
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteChannel(data).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
          this.getList()
        })
      }).catch(() => {
                
      });
    },
    handleView(row) {
      this.isDisabled = true
      this.form = Object.assign({}, row) // copy obj
      this.form.timestamp = new Date(this.form.timestamp)
      this.form.blnEnterprise = String(this.form.blnEnterprise)
      this.form.IDcard = this.form.creditNumber;
      this.dialogStatus = 'view'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.picFileList = []
      this.isDisabled = false
      this.form = Object.assign({}, row) // copy obj
      this.form.timestamp = new Date(this.form.timestamp)
      this.form.blnEnterprise = String(this.form.blnEnterprise)
      this.form.IDcard = this.form.creditNumber;
      this.dialogStatus = 'update'
      this.picFileList = [{name:'', url: '//' + this.form.logo, response:{url: '//' + this.form.logo}}]
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(!this.form.logo && this.form.blnEnterprise == 1){
            this.$message.warning('请上传logo图片!')
            return
          }
          if(this.form.blnEnterprise == 2){
            this.form.creditNumber = this.form.IDcard;
          }
          const tempData = Object.assign({}, this.form)
          addOrModifyChannel(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.form.id)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      getChannelList(this.params).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getPicFileList(imgList) {
      this.picFileList = imgList;
      if(imgList && imgList.length > 0){
        this.form.logo = imgList[0].response.data;
      }
    },
    blnStatus(blnEnterprise) {
      return blnEnterprise === 1 ? '是' : '否'
    },
    //企业logo
    beforeAvatarUpload(file){
      console.log('------------',file)
    },
    handleAvatarSuccess(res, file) {
      // console.log('444444444444',res, file)
      // this.imgList =  [{name: file.name, url:res.data}]
      this.form.logo = res.data;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      console.log('909',file)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    checkData (rule, value, callback) {
      if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
          callback(new Error('不能包含汉字!'));
        } else {
          callback();
        }
      }
      callback();
    }
  }
}
</script>

<style lang="scss">
  .channel-info .filter-item{
    margin-right: 10px;
  }
  .channnel-info-dialog .el-dialog{
    width: 30%
  }
  .channnel-info-dialog .el-dialog__footer{
    text-align: center
  }
  .channnel-info-dialog .el-dialog__body{
    padding: 30px 20px 0 20px;
  }
</style>
